package com.ylz.sjzx.sio.sdk.group.processor;

import com.alipay.remoting.AsyncContext;
import com.alipay.remoting.BizContext;
import com.alipay.remoting.rpc.protocol.AsyncUserProcessor;
import com.ylz.sjzx.sio.common.core.enums.Cmd;
import com.ylz.sjzx.sio.common.core.utils.GsonUtil;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import com.ylz.sjzx.sio.sdk.client.utils.ChatRoomMessageUtil;
import com.ylz.sjzx.sio.sdk.client.utils.SessionUtil;
import com.ylz.sjzx.sio.sdk.model.BaseSocketModel;
import com.ylz.sjzx.sio.sdk.model.ChatRoomMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author
 * @version 1.0
 * @date 2021/2/18
 */
@Component
@Slf4j
public class ChatRoomMessageProcessor extends AsyncUserProcessor<ChatRoomMessage> {
    @Override
    public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, ChatRoomMessage request) {
        log.debug("=========接收到客户端发来的消息========");
        log.debug(request.toString());
        if (StringUtils.equals(Cmd.manualKick.getValue(), request.getCmd().getValue())) {
            this.sendManualKick(request);
            return;
        }
        //判断是否只发给莫个人
        if (request.isSingle()) {
            this.sendSingleMessage(request);
            return;
        }
        ChatRoomMessageUtil.onlySendMessageByChatRoomMessage(request);
    }

    @Override
    public String interest() {
        return ChatRoomMessage.class.getName();
    }

    /**
     * 单独推给某个用户
     */
    private void sendManualKick(ChatRoomMessage chatRoomMessage) {
        IMSession bySid = SessionUtil.getIMSessionService().getBySid(chatRoomMessage.getSid());
        //先发送消息
        SessionUtil.sendMesage(bySid, GsonUtil.json22Bean((String) chatRoomMessage.getMessage(), BaseSocketModel.class));
        //逻登出上次的连接
        SessionUtil.getIMSessionService().logout(bySid.getSid());

    }

    private void sendSingleMessage(ChatRoomMessage chatRoomMessage) {
        IMSession bySid = SessionUtil.getIMSessionService().getBySid(chatRoomMessage.getSid());
        //先发送消息
        SessionUtil.sendMesage(bySid, GsonUtil.json22Bean((String) chatRoomMessage.getMessage(), BaseSocketModel.class));
    }
}
